<?php
namespace app\index\controller;
use think\Controller;
use think\Db;
use \think\View;

class Base extends Controller
{
	const NEWSCID = '100';//通知公告
	const UPNEWSCID = '101';
	const RESULTSCID = '102';
	protected $isLogin = true;
	public function __construct(){
		parent::__construct();
	}
	/**
	* 转换为JSON数据
	* @param int $code 状态码
	* @param String $msg 信息
	* @param array $data 数据
	* @return JSON
	*/

	public function _initialize() {
		$request  				   = request();
		$params 				   = $request->param();
		$model1 				   = Db::name('category');
		
		$map['type'] 			   = 'top';
		$header_menu 			   = $model1->where($map)->select();
		$map['type'] 			   = 'bottom';
		$footer_menu 			   = $model1->where($map)->select();	

		$this->assign('username', session('username'));
		$this->assign('post', session('post'));
		$this->assign('header', $header_menu);
		$this->assign('footer', $footer_menu);
	}

	public static function getJson($status, $msg="", $data=array()){
		$result = array(
			'status'	=>	$status,
			'msg'		=>	$msg,
			'data'		=>	$data
		);
		return json($result);
	}

	public function go_err() {
		$this->redirect('Pages/err');
	}

	public function auth() {
		$username 			= session('username');
		if(empty($username)) {
			$this->error('你还没有登陆', '/User/login');
			exit;
		}
	}

	public function ajaxReturn($data)
    {
      	return json($data);
    }

    public function succ($data, $msg = '获取数据成功') {
        $return 			= array(
            'msg'           => $msg,
            'status'        => 200,
            'data'          => $data
        );

        return json($return);
    }   

    public function erro($data = null, $msg = '获取数据失败') {
        $return 			= array(
            'msg'           => $msg,
            'status'        => 0,
            'data'          => $data
        );
        return json($return);
    }


	/**
	* 获取浏览者ip地址
	* @return String
	*/
	public function getClientIp(){
	    if(isset($_SERVER["HTTP_CLIENT_IP"]) and strcasecmp($_SERVER["HTTP_CLIENT_IP"], "unknown")){
	        return $_SERVER["HTTP_CLIENT_IP"];
	    }
	    if(isset($_SERVER["HTTP_X_FORWARDED_FOR"]) and strcasecmp($_SERVER[""], "unknown")){
	        return $_SERVER["HTTP_X_FORWARDED_FOR"];
	    }
	    if(isset($_SERVER["REMOTE_ADDR"])){
	        return $_SERVER["REMOTE_ADDR"];
	    }
	    return "";
	}

	// 正常化recommend category
    public function normal($d, $f = true) {
        if($f) {
            foreach($d as $k => &$v) {
                $v['title']             = $v['Lname'];
                $v['time']              = date('Y-m-d', $v['time']);
            }
        } else {
            $d['title']                 = $d['Lname'];
            $d['time']                  = date('Y-m-d', $d['time']);
        }

        return $d;
    }
}